package com.dabai.iot.core.utils;

import com.alibaba.fastjson.JSON;
import com.dabai.iot.core.tsl.TslBean;
import com.dabai.iot.core.tsl.TslBlock;
import com.dabai.iot.core.tsl.TslConstant;

import java.util.List;

/**
 * TSL 工具类
 *
 * @author kev1n
 */
public class TslUtil {

    /**
     * 默认物模型TSL
     */
    public static String resolveDefaultTsl(String productKey) {
        TslBean tsl = new TslBean();
        tsl.setVersion(TslConstant.TSL_VERSION);
        tsl.setProductKey(productKey);

        TslBlock block = new TslBlock();
        block.setBlockIdentifier(TslConstant.DEFAULT_BLOCK_ID);
        block.setBlockName(TslConstant.DEFAULT_BLOCK_NAME);
        tsl.setBlocks(List.of(block));

        return JSON.toJSONString(tsl);
    }

    /**
     * 根据数据类型转换值
     *
     * @param value    要转换的值
     * @param dataType 数据类型（Int, Float, Bool, String）
     * @return 转换后的值
     */
    public static Object convertValue(Object value, String dataType) {
        if (value == null) {
            return null;
        }

        String strValue = value.toString();
        if (strValue.isEmpty()) {
            return null;
        }

        try {
            return switch (dataType.toLowerCase()) {
                case "int32" -> {
                    if (value instanceof Number) {
                        yield ((Number) value).longValue();
                    }
                    yield Long.parseLong(strValue);
                }
                case "float" -> {
                    if (value instanceof Number) {
                        yield ((Number) value).doubleValue();
                    }
                    yield Double.parseDouble(strValue);
                }
                case "bool" -> Boolean.parseBoolean(strValue);
                default -> value; // 默认按原对象处理
            };
        } catch (NumberFormatException | NullPointerException e) {
            return null; // 转换失败
        }
    }

}
